﻿@using Contracts.Abstractions.Paging
@using WebAPP.Abstractions.Http
@using WebAPP.HttpClients
@using BlazorStrap
@using Contracts.Services.Catalog

@inject ICatalogHttpClient HttpClient
@inject IBlazorStrap BlazorStrap

<BSContainer>
    @if (_items.Any() is false)
    {
        <p>
            Nothing to show.
        </p>
    }
    else
    {
        <BSRow MarginTop="Margins.Large">
            @foreach (var item in _items)
            {
                <BSCard Class="w-25 border-0" Alignment="Alignment.Center" CardType="CardType.Card">
                    <BSCard Class="rounded-1" CardType="CardType.Image" src="placeholder:286x180"/>
                    <BSCard CardType="CardType.Body">
                        <BSCard CardType="CardType.Title">@item.Product.Name</BSCard>
                        <BSCard CardType="CardType.Subtitle">@item.Product.Description</BSCard>
                        @* <BSButton Color="BSColor.Warning" OnClick=@(() => EditAsync("New Title", catalog.ItemId))>Edit</BSButton> *@
                        @* <BSButton Color="BSColor.Danger" OnClick="() => DeleteAsync(catalog.ItemId)">Delete</BSButton> *@
                    </BSCard>
                </BSCard>
            }
        </BSRow>
        <BSPagination Align="Align.Center">
            <BSPaginationItem IsDisabled=@(_page.HasPrevious is false) @onclick="MoveToPreview">Previous</BSPaginationItem>
            @for (var paging = 1; paging <= _page.Current; paging++)
            {
                var current = paging;
                <BSPaginationItem @onclick=@(() => MoveToPage(current))>@current</BSPaginationItem>
            }
            <BSPaginationItem IsDisabled=@(_page.HasNext is false) @onclick="MoveToNext">Next</BSPaginationItem>
        </BSPagination>
    }
</BSContainer >

@code {

    private readonly CancellationTokenSource _cancellationTokenSource = new();

    private List<Projection.CatalogItemListItem> _items;
    private Page _page;

    protected override async Task OnInitializedAsync()
        => await FetchDataAsync();

    private async Task FetchDataAsync(int limit = 8, int offset = 0)
    {
        var response = await HttpClient.GetAllItemsAsync(limit, offset, _cancellationTokenSource.Token);

        if (response.Success)
        {
            _items = response.ActionResult.Items.ToList();
            _page = response.ActionResult.Page;
        }
    }

    private Task MoveToPage(int current)
        => FetchDataAsync(offset: current - 1);

    private async Task MoveToNext()
    {
        if (_page.HasNext)
            await FetchDataAsync(offset: _page.Current);
    }

    private async Task MoveToPreview()
    {
        if (_page.HasPrevious)
            await FetchDataAsync(offset: _page.Current - 2);
    }

    private void Dispose()
        => _cancellationTokenSource.Cancel();

}